package com.jxc.action.kcgl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.jxc.action.BaseAction;
import com.jxc.dao.BaseDaoI;
import com.jxc.model.po.Fhtj;
import com.jxc.model.po.Goods;
import com.jxc.model.po.GoodsRepertory;
import com.jxc.model.vo.Json;
import com.jxc.model.vo.SessionInfo;
import com.jxc.model.vo.VGoods;
import com.jxc.model.vo.VGoodsRepertory;
import com.jxc.model.vo.VDeliverlist;
import com.jxc.model.vo.VDeliverlistItem;
import com.jxc.model.vo.VUser;
import com.jxc.service.GoodsRepertoryServiceI;
import com.jxc.service.GoodsServiceI;
import com.jxc.service.RepertoryServiceI;
import com.jxc.service.DeliverlistItemServiceI;
import com.jxc.service.DeliverlistServiceI;
import com.jxc.service.UserServiceI;
import com.jxc.util.ExceptionUtil;
import com.jxc.util.ResourceUtil;
import com.opensymphony.xwork2.ModelDriven;

@Namespace("/kcgl")
@Action(value = "goodsDeliverAction", results = { @Result(name = "goodsDeliver", location = "/amountRelate/goodsDeliver.jsp"),
		 @Result(name = "goodsReceive", location = "/amountRelate/goodsReceive.jsp")})
public class GoodsDeliverAction extends BaseAction implements ModelDriven<VDeliverlist> {
	private final static Logger logger = LoggerFactory.getLogger(GoodsDeliverAction.class);

	private VDeliverlist model = new VDeliverlist();
	private String items;
	private String nums;

	@Autowired
	private BaseDaoI<Goods> goodsDao;
	@Autowired
	private BaseDaoI<GoodsRepertory> goodsreperDao;
	@Autowired
	private GoodsRepertoryServiceI goodsreperserI;
	@Autowired
	private DeliverlistServiceI deliverlistService;
	@Autowired
	private DeliverlistItemServiceI deliverlistItemService;
	@Autowired
	private UserServiceI userService;
	@Autowired
	private RepertoryServiceI repertoryService;
	@Autowired
	private GoodsServiceI goodsService;

	public String goodsDeliver() {
		getSubAuths("JXSGL_FHGL");
		return "goodsDeliver";
	}
	
	public String goodsReceive() {
		getSubAuths("WDDLS_SHGL");
		return "goodsReceive";
	}

	public String goodsDeliverItem() {
		return "goodsDeliverItem";
	}

	public void datagrid() throws Exception {
		if (model.getBeginDate() != null) {
			String beginDateStr = new SimpleDateFormat("yyyy-MM-dd").format(model.getBeginDate());
			model.setBeginDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(beginDateStr + " 00:00:00"));
		}
		if (model.getEndDate() != null) {
			String endDateStr = new SimpleDateFormat("yyyy-MM-dd").format(model.getEndDate());
			model.setEndDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endDateStr + " 23:59:59"));
		}
		if (model.getOrid() != null) {
			this.writeJson(deliverlistService.datagrid(model));
		} else {
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get(sessionInfo.getUserId());
			if (vuser.getReid() != null) {
				model.setRid(vuser.getReid());
				model.setAgencyId(vuser.getUpid());
				this.writeJson(deliverlistService.datagrid(model));
			} else {
				model.setAgencyId(vuser.getId());
				System.out.println(vuser.getId());
				this.writeJson(deliverlistService.datagrid(model));
			}
		}
	}
	
	public void datagridForDealer() throws Exception {
		if (model.getBeginDate() != null) {
			String beginDateStr = new SimpleDateFormat("yyyy-MM-dd").format(model.getBeginDate());
			model.setBeginDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(beginDateStr + " 00:00:00"));
		}
		if (model.getEndDate() != null) {
			String endDateStr = new SimpleDateFormat("yyyy-MM-dd").format(model.getEndDate());
			model.setEndDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endDateStr + " 23:59:59"));
		}
		if (model.getOrid() != null) {
			this.writeJson(deliverlistService.datagrid(model));
		} else {
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get(sessionInfo.getUserId());
			if (vuser.getReid() != null) {
				model.setRid(vuser.getReid());
				model.setDealerId(vuser.getUpid());
				this.writeJson(deliverlistService.datagrid(model));
			} else {
				model.setDealerId(vuser.getId());
				this.writeJson(deliverlistService.datagrid(model));
			}
		}
	}

	public void noAuth_search() {
		this.writeJson(this.deliverlistService.combobox(model));
	}

	/**
	 * 发货单添加
	 */
	public void add() {
		// 判断调出库存是否有足够的库存量
		Json j = new Json();
		try {
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get(sessionInfo.getUserId());
			if (vuser.getReid() != null) {
				model.setAgencyId(vuser.getUpid());
			} else {
				model.setAgencyId(vuser.getId());
			}
			int total = 0;
			Map<Long, VDeliverlistItem> itemMap = new HashMap<Long, VDeliverlistItem>();
			List<VDeliverlistItem> vdlis = new ArrayList<VDeliverlistItem>();
			if (StringUtils.isNotBlank(items)) {
				String[] itemInfos = items.split(",");
				String[] numsinfo = model.getNums().split(",");
				String[] pricesinfo = model.getPrices().split(",");
				for (int i = 0; i < itemInfos.length; i++) {
					String goodsId = itemInfos[i];
					String num = numsinfo[i];
					String price = pricesinfo[i];
					total += Integer.parseInt(num);
					VDeliverlistItem vdli = itemMap.get(Long.parseLong(goodsId));
					if (vdli == null) {
						vdli = new VDeliverlistItem();
						vdli.setGid(Long.parseLong(goodsId));
						vdli.setPrice(Double.parseDouble(price));
						vdli.setNum(Integer.parseInt(num));
						vdlis.add(vdli);
					} else {
						vdli.setPrice(Double.parseDouble(price));
						vdli.setNum(vdli.getNum() + Integer.parseInt(num));
					}
					itemMap.put(Long.parseLong(goodsId), vdli);
				}
			}
		
			model.setNum(total);
			Long tlid = deliverlistService.save(model);
			deliverlistItemService.batchSave(vdlis, tlid);
			j.setMsg("添加成功！");
			j.setSuccess(true);
		} catch (Exception e) {
			j.setMsg("添加失败！");
			e.printStackTrace();
			logger.info(ExceptionUtil.getExceptionMessage(e));
		}
		super.writeJson(j);
	}

	/**
	 * 修改调拔单
	 * 
	 */
	public void edit() {
		Json j = new Json();
		try {
			//model.setIds(ids)
			model.setIsInConfirm(false);
			model.setIsOutConfirm(false);
			deliverlistService.update(model);
			
//			transferlistItemService.update();
			j.setSuccess(true);
			j.setMsg("编辑成功！");
		} catch (Exception e) {
			logger.error(ExceptionUtil.getExceptionMessage(e));
			j.setMsg("编辑失败！");
			e.printStackTrace();
		}
		super.writeJson(j);
	}

	/**
	 * 删除调拔单
	 * 
	 */
	public void delete() {
		// 判断要删除的调拔单中是否已经确认过，只有未确认过的调拔单才能删除
		Json j = new Json();
		deliverlistService.delete(model.getIds());
		j.setSuccess(true);
		j.setMsg("删除成功!");
		super.writeJson(j);
	}
	
	/*
	 * 查询发货明细返回goods json数组给前端
	 */
	public void findGoods(){
		try {
			List<VGoods> vg = new ArrayList<VGoods>();
			vg = goodsService.findGoods(model.getItemsid());
			this.writeJson(vg);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 */
	public void findGoodsDeliver(){
		try {
			List<VGoods> vg = new ArrayList<VGoods>();
			vg = goodsService.findGoodsDeliver(model.getItemsid());
			this.writeJson(vg);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 确认调出调拔单
	 * 
	 */
	public void outConfirm() {
		Json j = new Json();
		try {
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
			List<VDeliverlist> vtls = deliverlistService.combobox(model);
			VDeliverlist vtl = vtls.get(0);
			if (vtl.getIsOutConfirm()==true) {
				j.setMsg("该调拔单已被确认！");
			} 
			else {
				vtl.setOcuid(sessionInfo.getUserId());
				vtl.setOutConfirmDate(new Date());
				vtl.setIsOutConfirm(true);
				deliverlistService.update(vtl);
				j.setMsg("确认成功!");
			}
			j.setSuccess(true);
		} catch (Exception e) {
			j.setMsg("该调拔单失败！");
			e.printStackTrace();
		}

		super.writeJson(j);
	}

	/**
	 * 确认调入调拔单
	 * 
	 */
	public void inConfirm() {
		Json j = new Json();
		try {
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
			List<VDeliverlist> vtls = deliverlistService.combobox(model);
			VDeliverlist vtl = vtls.get(0);
			if (vtl.getIsInConfirm()==true) {
				j.setMsg("该调拔单已被确认!");
			} else {
				vtl.setIcuid(sessionInfo.getUserId());
				vtl.setInConfirmDate(new Date());
				vtl.setIsInConfirm(true);
				deliverlistService.update(vtl);

				VDeliverlistItem param = new VDeliverlistItem();
				param.setDlid(model.getId());
				List<VDeliverlistItem> items = deliverlistItemService.combobox(param);
				for (VDeliverlistItem item : items) {
					VGoodsRepertory vGoodsRepertory = new VGoodsRepertory();
					vGoodsRepertory.setGid(new Long(item.getGid()));
					vGoodsRepertory.setOrid(vtl.getOrid());
//					vGoodsRepertory.setIrid(model.getIrid());
					vGoodsRepertory.setNum(new Integer(item.getNum()));
					goodsreperserI.findOut(vGoodsRepertory);
					System.out.println(vtl.getIrid());
        			vGoodsRepertory.setIrid(vtl.getIrid()); 
					goodsreperserI.findCounts(vGoodsRepertory);
				}

				j.setMsg("确认成功!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	
		j.setSuccess(true);
		super.writeJson(j);
	}
	
	/**
	 * 发货统计
	 * 统计向每个经销商发货的数目，绘制三维柱状图
	 */
	public String deliverTotal() {
		try {
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get(sessionInfo.getUserId());
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("image/jpeg");
			List<Fhtj> fhtjList = deliverlistService.findFhsum(vuser.getUpid());
			JFreeChart chart = deliverlistService.getDeliverChart(fhtjList);
			ChartUtilities.writeChartAsJPEG(response.getOutputStream(), chart, 300, 500);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
		
	@Override
	public VDeliverlist getModel() {
		return model;
	}

	public String getItems() {
		return items;
	}

	public void setItems(String items) {
		this.items = items;
	}

	public String getNums() {
		return nums;
	}

	public void setNums(String nums) {
		this.nums = nums;
	}

}
